import { useContext, useEffect, useRef, useState } from 'react'
import '../assets/cpu.css'
import GlobalContext from './GlobalContext'
import Cores from './Cores'
import Line from './Line'
import * as echarts from 'echarts'

const { contentStyle, setHt, getCpuOption } = window.api.cpu

function Cpu(props) {
  const { t } = useContext(GlobalContext)
  const cpuChartRef = useRef()

  useEffect(() => {
    setHt(props.cpu)
  }, [props.cpu])

  useEffect(() => {
    let cpuChart = echarts.getInstanceByDom(cpuChartRef.current)
    if (!cpuChart) {
      cpuChart = echarts.init(cpuChartRef.current)
    }
    cpuChart.setOption(getCpuOption(t, props.loadInfo))
  }, [props.loadInfo, t])

  return (
    <GlobalContext.Consumer>
      {(ctx) => {
        return (
          <div style={contentStyle()}>
            {/* cpu 基本信息 */}
            <div className="cpu-usage">
              <span className="cpu-usage-item">
                <span>
                  <span className="square" />
                  {ctx.t('brand')}
                </span>
                <span>{props.cpu ? props.cpu.brand : ''}</span>
              </span>
              <span className="cpu-usage-item">
                <span>
                  <span className="square" />
                  {ctx.t('cores')}
                </span>
                <span>{props.cpu ? props.cpu.cores : ''}</span>
              </span>
              <span className="cpu-usage-item">
                <span>
                  <span className="square" />
                  {ctx.t('phyCores')}
                </span>
                <span>{props.cpu ? props.cpu.physicalCores : ''}</span>
              </span>
              <span className="cpu-usage-item">
                <span>
                  <span className="square" />
                  {ctx.t('sped')}
                </span>
                <span>{props.cpu ? props.cpu.speed : ''} GHz</span>
              </span>
            </div>
            <Line />
            {/* cpu 平均使用率 */}
            <div className="cpu-avg-usage">
              <div
                id="cpu-chart"
                ref={cpuChartRef}
                style={{
                  width: '100%',
                  height: '80px'
                }}
              ></div>
            </div>
            <Line />
            {/* 所有核心使用率 */}
            {props.loadInfo && props.loadInfo.cpus && <Cores cpus={props.loadInfo.cpus} />}
            <Line />
          </div>
        )
      }}
    </GlobalContext.Consumer>
  )
}

export default Cpu
